import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;




public class MessageSender{	
	
	private DatagramSocket socket;
	
	public MessageSender(){		
		try{
			socket=new DatagramSocket();
		}catch(SocketException e){
			e.printStackTrace();
		}		
	}
	
	
	
	public void send(User recipient,String strMsg){
		try{
			InetAddress address = InetAddress.getByName(recipient.getAddress());
			
					
			Message msg=new Message(Utility.getNickName(),recipient.getNickName(),strMsg);
			
			//Deserialize the message to byte[]
			byte[] buf=msg.toBytes();
			
			DatagramPacket packet = new DatagramPacket(buf, buf.length,address,recipient.getPort());
			socket.send(packet);
			
			//System.out.println("Client send data to <" + recipient.getAddress() + ":" + recipient.getPort() + "> at " + java.util.Calendar.getInstance().getTime().toString());
			
		}catch(UnknownHostException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
	}	
	
	
}
